package com.zhentao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhentao.pojo.TbBlog;
import com.zhentao.service.TbBlogService;
import com.zhentao.service.impl.TbBlogServiceImpl;
import com.zhentao.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/blog")
public class BlogController {
    @Autowired
    private TbBlogServiceImpl tbBlogService;
    @Autowired
    private TbBlogService blogService;

    @RequestMapping("/findAll")
    public List<TbBlog> findAll(){
        return tbBlogService.list();
    }
    @RequestMapping("/findById")
    public TbBlog findById(String Id){
        QueryWrapper<TbBlog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(Id!=null,"id",Id);
        return tbBlogService.getOne(queryWrapper);
    }
    
    @RequestMapping("/findBy")
    public TbBlog findBy(String id){
        if (id == null || id.isEmpty()) {
            return null;
        }
        
        try {
            // 尝试通过ID查询博客
            return tbBlogService.getById(id);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    @RequestMapping("/add")
    public String add(@RequestBody TbBlog tbBlog){
        TbBlog tbBlog1 = new TbBlog();
        tbBlog1.setUserId(tbBlog.getUserId());
        tbBlog1.setTitle(tbBlog.getTitle());
        tbBlog1.setImages(tbBlog.getImages());
        tbBlog1.setContent(tbBlog.getContent());
        tbBlog1.setCreateTime(new Date());
        tbBlogService.save(tbBlog);
        return "新增成功";
    }
    
    /**
     * 博客点赞/取消点赞
     * @param id 博客ID
     * @param userId 用户ID（通过请求参数传递）
     * @return 点赞数据
     */
    @GetMapping("/likes/{id}")
    public Result likeBlog(@PathVariable("id") Long id, @RequestParam(value = "userId", required = false) String userId) {
        return blogService.likeBlog(id, userId);
    }

    @GetMapping("/isLiked/{id}")
    public Result isLiked(@PathVariable("id") Long id, @RequestParam(value = "userId", required = false) String userId) {
        return blogService.isLiked(id, userId);
    }

//    /**
//     * 点赞或取消点赞博客
//     * @param params 包含blogId和isLike的参数
//     * @return 操作结果
//     */
//    @PostMapping("/blog/like")
//    public Map<String, Object> like(@RequestBody Map<String, Object> params) {
//        Map<String, Object> result = new HashMap<>();
//
//        try {
//            System.out.println("收到点赞请求，参数: " + params);
//
//            Object blogIdObj = params.get("blogId");
//            Object isLikeObj = params.get("isLike");
//
//            System.out.println("blogId类型: " + (blogIdObj != null ? blogIdObj.getClass().getName() : "null"));
//            System.out.println("isLike类型: " + (isLikeObj != null ? isLikeObj.getClass().getName() : "null"));
//
//            if (blogIdObj == null || isLikeObj == null) {
//                result.put("code", -1);
//                result.put("msg", "参数错误: 缺少必要参数");
//                return result;
//            }
//
//            // 转换参数类型
//            String blogId;
//            Boolean isLike;
//
//            if (blogIdObj instanceof Integer) {
//                blogId = String.valueOf(blogIdObj);
//            } else if (blogIdObj instanceof String) {
//                blogId = (String) blogIdObj;
//            } else {
//                result.put("code", -1);
//                result.put("msg", "参数错误: blogId类型不正确");
//                return result;
//            }
//
//            if (isLikeObj instanceof Boolean) {
//                isLike = (Boolean) isLikeObj;
//            } else if (isLikeObj instanceof String) {
//                isLike = Boolean.valueOf((String) isLikeObj);
//            } else if (isLikeObj instanceof Integer) {
//                isLike = ((Integer) isLikeObj) > 0;
//            } else {
//                result.put("code", -1);
//                result.put("msg", "参数错误: isLike类型不正确");
//                return result;
//            }
//
//            System.out.println("处理后的参数 - blogId: " + blogId + ", isLike: " + isLike);
//
//            TbBlog blog = tbBlogService.getById(blogId);
//            if (blog == null) {
//                result.put("code", -1);
//                result.put("msg", "博客不存在");
//                return result;
//            }
//
//            // 更新点赞数
//            Integer currentLikes = blog.getLiked() == null ? 0 : blog.getLiked();
//            System.out.println("当前点赞数: " + currentLikes);
//
//            if (isLike) {
//                blog.setLiked(currentLikes + 1);
//            } else {
//                // 确保点赞数不为负数
//                blog.setLiked(Math.max(0, currentLikes - 1));
//            }
//
//            System.out.println("更新后点赞数: " + blog.getLiked());
//
//            boolean success = tbBlogService.updateById(blog);
//
//            if (success) {
//                result.put("code", 0);
//                result.put("msg", isLike ? "点赞成功" : "取消点赞成功");
//                result.put("data", blog.getLiked());
//            } else {
//                result.put("code", -1);
//                result.put("msg", "操作失败");
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            result.put("code", -1);
//            result.put("msg", "操作失败: " + e.getMessage());
//        }
//
//        System.out.println("点赞处理结果: " + result);
//        return result;
//    }
    /**
     * 删除博客
     * @param params 包含id的参数
     * @return 操作结果
     */
    @PostMapping("/delete")
    public Map<String, Object> deleteBlog(@RequestBody Map<String, Object> params) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            Object idObj = params.get("id");
            
            if (idObj == null) {
                result.put("code", -1);
                result.put("msg", "参数错误: 缺少必要参数");
                return result;
            }
            
            String id;
            if (idObj instanceof Integer) {
                id = String.valueOf(idObj);
            } else if (idObj instanceof String) {
                id = (String) idObj;
            } else {
                result.put("code", -1);
                result.put("msg", "参数错误: id类型不正确");
                return result;
            }
            
            // 查询博客是否存在
            TbBlog blog = tbBlogService.getById(id);
            if (blog == null) {
                result.put("code", -1);
                result.put("msg", "博客不存在");
                return result;
            }
            
            // 删除博客
            boolean success = tbBlogService.removeById(id);
            
            if (success) {
                result.put("code", 0);
                result.put("msg", "删除成功");
            } else {
                result.put("code", -1);
                result.put("msg", "删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", -1);
            result.put("msg", "删除失败: " + e.getMessage());
        }
        
        return result;
    }
    @RequestMapping("/findUserById")
    public Map<String, Object> findUserById(@RequestParam("id") String userId){
        Map<String, Object> result = new HashMap<>();
        try {
            if (userId == null || userId.isEmpty()) {
                result.put("code", -1);
                result.put("msg", "用户ID不能为空");
                return result;
            }
            
            QueryWrapper<TbBlog> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId);
            // 只查询包含图片的博客
            queryWrapper.isNotNull("images");
            queryWrapper.ne("images", "");
            // 按时间降序排序
            queryWrapper.orderByDesc("create_time");
            
            List<TbBlog> blogs = tbBlogService.list(queryWrapper);
            
            // 构建用户相册数据
            List<Map<String, Object>> albumPhotos = new ArrayList<>();
            for (TbBlog blog : blogs) {
                Map<String, Object> photo = new HashMap<>();
                photo.put("id", blog.getId());
                photo.put("url", blog.getImages());
                photo.put("description", blog.getContent());
                photo.put("createTime", blog.getCreateTime());
                albumPhotos.add(photo);
            }
            
            result.put("code", 0);
            result.put("msg", "获取相册成功");
            result.put("data", albumPhotos);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", -1);
            result.put("msg", "获取相册失败: " + e.getMessage());
        }
        return result;
    }
}
